#include <stdio.h>
#include <stdlib.h>
#include <check.h>
#include <signal.h>
#include <mqueue.h>
#include <math.h>
#include "../../ChaineCond/ResChaineCond.h"
#include "../../ChaineCond/init_functions.h"
#include "../../ChaineCond/mise_en_carton.h"
#include "../../interface/partage_simu.h"
#include "../../interface/constantes.h"
#include "../../interface/messqueue.h"
#include "../../interface/mutexpartage.h"
#include "../../interface/variablesglobales.h"

static mqd_t bal_erreurs;
static mqd_t bal_carton;
static mqd_t bal_palettes;
static mqd_t bal_messages;
static mqd_t bal_impression;
static mqd_t bal_impression;


START_TEST (arrive_carton) {
	int i;	
	g_shm->dim = 200;
	for (i = 0; i < g_nb_piec_cart_a; i++) {
		arrivee_piece_handler();
	}
	
	//il doit y avoir un message dans la boite carton
	struct mq_attr attr;
	mq_getattr(bal_carton, &attr);
	fail_unless(attr.mq_curmsgs == 1,
		"erreur carton plein non validé\n");

	//me message doit être de type IMPRIMER
	struct message msg_recu;
	lire_message(bal_carton, &msg_recu);
    	fail_unless(msg_recu.type == IMPRIMER, 
		"erreur message carton plein\n");
}
END_TEST

START_TEST (arrive_piece_mauvaise_dimension) {
	int i;
	g_shm->dim = 205;
	for (i = 0; i < ceil((double)g_seuil_defect_a * (double)g_nb_piec_cart_a / 10000.0) ; i++) {
		arrivee_piece_handler();
	}
	
	//il doit y avoir un message dans la boite carton
	struct mq_attr attr;
	mq_getattr(bal_erreurs, &attr);
	fail_unless(attr.mq_curmsgs == 1,
		"erreur arrivée trop de pièces de mauvaise dimensions non signalée\n");

	struct message msg_erreur;
	lire_message(bal_erreurs, &msg_erreur);
    	fail_unless(msg_erreur.type == ERRDEFECT, 
		"erreur mauvais message arrivée trop de pièces de mauvaise dimensions\n");
}
END_TEST

void setup() {
	set_test_values();
	init_shm();
	g_shm->carton = OK;
	init_boite_au_lettres();
	creer_mqueue(BAL_ERREURS_NAME, BAL_NB_MAX_MESSAGE_DEFAUT);
	creer_mqueue(BAL_MESSAGES_NAME, BAL_NB_MAX_MESSAGE_DEFAUT);
	init_mise_en_carton();
	charger_lot(NUM_A);

	bal_carton = ouvrir_mqueue(BAL_CARTONS_NAME, O_RDONLY);
	bal_erreurs = ouvrir_mqueue(BAL_ERREURS_NAME, O_RDONLY);
}

void teardown() {
	mq_close(bal_erreurs);
	mq_close(bal_messages);
	mq_close(bal_carton);
	mq_close(bal_palettes);
	mq_close(bal_impression);
	
	mq_unlink(BAL_ERREURS_NAME);
	mq_unlink(BAL_MESSAGES_NAME);
	mq_unlink(BAL_CARTONS_NAME);
	mq_unlink(BAL_IMPRESSION_NAME);
	mq_unlink(BAL_PALETTES_NAME);
}

Suite * mise_en_carton_suite(void) {
	Suite *s = suite_create("Cartons");
	/* Serialiseur test case */
	TCase *tc_arrivee_carton = tcase_create("Arrive_carton");
	tcase_add_checked_fixture(tc_arrivee_carton, setup, teardown);
	tcase_add_test(tc_arrivee_carton, arrive_carton);
	tcase_add_test(tc_arrivee_carton, arrive_piece_mauvaise_dimension);
	suite_add_tcase(s, tc_arrivee_carton);


	return s;
}
